package com.ljh.server.handler;

import com.ljh.message.ChatRequestMessage;
import com.ljh.message.ChatResponseMessage;
import com.ljh.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author: Themberfue
 * @date: 2025/5/29 21:03
 * @description:
 */
// ! 很重要！！！这里踩坑了（因为没加这个，Netty 会直接抛异常，并断开连接）
@ChannelHandler.Sharable
public class ChatRequestHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String to = msg.getTo();
        Channel channel = SessionFactory.getSession().getChannel(to);
        // ? 在线
        ChatResponseMessage response;
        if (channel != null) {
            response = new ChatResponseMessage(msg.getFrom(), msg.getContent());
            channel.writeAndFlush(response);
        } else { // ? 下线
            response = new ChatResponseMessage(false, "对方不存在或者下线");
            ctx.writeAndFlush(response);
        }
    }
}
